package calao.contact.client;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.TextBox;

import calao.client.ServiceCallback;
import calao.client.ui.Form;
import calao.client.ui.HasTitle;
import calao.client.ui.RegexTextBox;

public class GroupForm 
extends Form
implements HasTitle
{
	
	class CreateCallback extends ServiceCallback {
		protected void onReturn(Object obj) {
			mod.refreshGroups();
			defer(new Command() {
				public void execute() {
					parentGroupList.refresh();
					mod.getDesktop().popView();
				}				
			});
		}
	}
	
	class SaveCallback extends ServiceCallback {
		final Group group;
		SaveCallback(Group group) {
			this.group = group;
		}
		protected void onReturn(Object obj) {
			mod.refreshGroups();
			defer(new Command() {
				public void execute() {
					parentGroupTable.onGroupModified();
					setChangesSaved();
				}				
			});
		}
	}

	final ContactMod mod = ContactMod.instance;

	final GroupList parentGroupList;

	final Group group;
	final ContactTable parentGroupTable;

	final RegexTextBox nameBox = new RegexTextBox(".+");
	final TextBox descBox = new TextBox();
	
	GroupForm(GroupList parent)
	{
		super(CREATE);
		this.parentGroupList = parent;
		this.group = null;
		this.parentGroupTable = null;
		setTitle(mod.text.newGroup());		
		build();
	}
	
	GroupForm(Group group, ContactTable parent)
	{
		super(CHANGE);
		this.parentGroupList = null;
		this.group = group;
		this.parentGroupTable = parent;
		setTitle(mod.text.editGroup());		
		build();
		reset();
	}
	
	void build()
	{
		add(mod.text.name(), nameBox);
		add(mod.text.description(), descBox);
	}
	
	Group getInput()
	{
		Group group = new Group();
		if (this.group!=null) group.setId(this.group.id);
		group.setDescription(descBox.getText());
		group.setName(nameBox.getText());
		return group;
	}
	
	public void create()
	{
		mod.service.createGroup(getInput(), new CreateCallback());
	}
	
	public void saveChanges()
	{
		Group input = getInput();
		mod.service.save(input, new SaveCallback(input));		
	}
	
	public void reset()
	{
		nameBox.setText(group.getName());
		descBox.setName(group.description);
	}
	
}
